package com.lin.seckilllcw.controller;

import com.alibaba.fastjson.JSON;
import com.lin.seckilllcw.config.AccessLimit;
import com.lin.seckilllcw.exception.GlobalException;
import com.lin.seckilllcw.pojo.Order;
import com.lin.seckilllcw.pojo.SeckillMessage;
import com.lin.seckilllcw.pojo.SeckillOrder;
import com.lin.seckilllcw.pojo.User;
import com.lin.seckilllcw.rabbitmq.MQSender;
import com.lin.seckilllcw.service.IGoodsService;
import com.lin.seckilllcw.service.IOrderService;
import com.lin.seckilllcw.service.ISeckillOrderService;
import com.lin.seckilllcw.vo.GoodsVo;
import com.lin.seckilllcw.vo.RespBean;
import com.lin.seckilllcw.vo.RespBeanEnum;
import com.rabbitmq.tools.json.JSONUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**秒杀
 * @author ChenweiLin
 * @create 2021-07-31 23:15
 */
@Controller
@RequestMapping("/seckill")
@Slf4j
public class SecKillController implements InitializingBean {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private RedisScript<Long> script;

    private Map<Long,Boolean> EmptyStockMap = new HashMap<>();
    /**
     *秒杀
     * windows优化前QPS：219 且有超卖现象
     *  redis+页面静态化：QPS:629
     */
//    @RequestMapping("/doSeckill2")
//    public String doSeckill2(Model model, User user,Long goodsId){
//        //第一步：判断用户是否为空
//        if(user == null){
//            return "login";
//        }
//        //第二步：判断库存
//        model.addAttribute("user", user);
//        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
//        if(goods.getStockCount() < 1){
//            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
//            return "secKillFail";
//        }
//        //第三步：判断是否重复抢购
//        SeckillOrder seckillOrder =
//                        seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId())
//                        .eq("goods_id", goodsId));
//
//        if(seckillOrder != null){
//            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
//            return "secKillFail";
//        }
//        //第四步：进入秒杀
//        Order order = orderService.seckill(user,goods);
//        model.addAttribute("order",order);
//        model.addAttribute("goods", goods);
//
//        return "orderDetail";
//
//
//    }


    /**
     * 秒杀页面静态化
     * windows优化前QPS：785 且有超卖现象
     * redis+页面静态化：QPS:1356
     * 服务优化完，流量削峰+redis预减库存：2454
     */
    @PostMapping("/{path}/doSeckill")
    @ResponseBody
    public RespBean doSeckill(@PathVariable String path, Model model, User user, Long goodsId) {
        //第一步：判断用户是否为空
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        /*
        //第二步：判断库存
        model.addAttribute("user", user);
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        if(goods.getStockCount() < 1){
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //第三步：判断是否重复抢购 一个人只能抢一个商品
        //防止超卖
        SeckillOrder seckillOrder = (SeckillOrder)redisTemplate.opsForValue()
                .get("order:" + user.getId() + ":" + goods.getId());

        if(seckillOrder != null){
            RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }

        //第四步：进入秒杀
        Order order = orderService.seckill(user,goods);
        return RespBean.success(order);
         */


        ValueOperations valueOperations = redisTemplate.opsForValue();
        //随机url检测
        boolean check = orderService.check(user,goodsId,path);
        if(!check){
            return RespBean.error(RespBeanEnum.REQUEST_ILLEGAL);
        }

        //判断是否重复抢购
        //防止超卖
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue()
                .get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记，减少redis的访问
        if(EmptyStockMap.get(goodsId)){
            return  RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //预减库存的操作
//        Long stock = valueOperations.decrement("seckillGoods" + goodsId);
        //用lua脚本实现redis分布式锁
        Long stock = (Long) redisTemplate.execute(script, Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST);

        if(stock < 0){
            EmptyStockMap.put(goodsId, true);
            valueOperations.increment("seckillGoods" + goodsId);//此行是为了让redis若预减为-1，再加上1 让redis的库存与db中的保持一致
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        SeckillMessage seckillMessage = new SeckillMessage(user, goodsId);

        //因为用了rabbitMq，变成了异步操作，能快速返回库存结果，会提供一个流量削峰的作用
        mqSender.sendSeckillMessage(JSON.toJSONString(seckillMessage));

        return  RespBean.success(0);

    }



    @GetMapping("/result")
    @ResponseBody
    public RespBean getResult(User user,Long goodsId){
        if(user == null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(user, goodsId);
        return RespBean.success(orderId);
    }

    /**
     * 获取随机url地址传给前端
      * @param user
     * @param goodsId
     * @return
     */
    @AccessLimit(second=5,maxCount=5,needLogin=true)
    @GetMapping("/path")
    @ResponseBody
    public RespBean getPath(User user, Long goodsId, String captcha, HttpServletRequest request){
        if (user == null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //限制访问次数，5秒内访问5次
        String uri = request.getRequestURI();
        captcha = "0";
        Integer count = (Integer)valueOperations.get(uri + ":" + user.getId());
        if(count == null){
            valueOperations.set(uri + ":" + user.getId(), 1, 5,TimeUnit.SECONDS);
        }else if (count < 5){
            valueOperations.increment(uri + ":" + user.getId());
        }else {
            return RespBean.error(RespBeanEnum.ACCESS_LIMIT_REAHCED);
        }

        boolean check = orderService.check(user, goodsId, captcha);
        if(!check)
            return RespBean.error(RespBeanEnum.ERROR_CAPTCHA);

        String str = orderService.createPath(user,goodsId);

        return RespBean.success(str);
    }

    /**
     * 验证码
     */
    @GetMapping("/captcha")
    @ResponseBody
    public void verifyCode(User user, Long goodsId, HttpServletResponse response){
        if(user == null || goodsId <0){
            throw new GlobalException(RespBeanEnum.REQUEST_ILLEGAL);
        }
        //设置请求头为输出的图片的类型
        response.setContentType("image/jpg");
        response.setHeader("Pargam", "No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        //生成验证码，将结果放入Redis
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        redisTemplate.opsForValue().set("captcha"+user.getId()+":"+goodsId, captcha.text(), 300, TimeUnit.SECONDS);
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 系统初始化，把商品库存数量加载到Redis
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        //redis提前获取库存
        list.forEach(goodsVo ->{
                redisTemplate.opsForValue().set("seckillGoods"+goodsVo.getId(), goodsVo.getStockCount());
                EmptyStockMap.put(goodsVo.getId(), false);
                }
        );
    }
}
